import Holiday from "./holiday.js";

/**
 * [dateFormat 格式化日期时间]
 * @param  {[datetimeString]} [dt]  [要转化的时间日期,留空代表当前时间]
 * @param  {[string]} fmt [格式 'yyyy-MM-dd hh:mm:ss' ]
 * @return {[datetimeString]}     [新时间日期]
 */
const dateFormat = (fmt, dt = null) => {
  // console.log('dt,dt.length:',typeof dt, dt,dt?dt.length:0)
  var date = dt ? new Date((typeof dt) === 'string' ? dt.replace(/-/g, '/') : dt) : new Date();
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  // console.log('格式化后的时间为：', fmt);
  return fmt;
}

/**
 * [getDate 获取时间日期及天数]
 * @param  {[Boolean]} [havesec] [是否精确到秒]
 * @return {[object]}         [description]
 */
const getDT = (now) => {
  var now = (typeof dt) === 'undefined' ? new Date() : new Date(dt);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();

  var nowYM = year + '-' + fixZero(month);
  var nowDate = year + '-' + fixZero(month) + '-' + fixZero(day);
  var nowTime = fixZero(hour) + ':' + fixZero(minute) + ':' + fixZero(second);

  //返回的时间对象
  var nowDT = {
    lastday: new Date(year, month, 0).getDate(), //根据 日期数值的越界进位、退位，下个月的第0天就是当月的最后一天   
    nowYM: nowYM, //日期
    nowdate: nowDate, //日期
    nowtime: nowTime, //时间
    nowdatetime: nowDate + ' ' + nowTime, //当前时间日期
  }
  console.log('时间日期，月天数对象：', nowDT);
  return nowDT;
}

const diffDate = function (endDT, startDT) {
  endDT = endDT.indexOf('-') > 0 ? endDT.replace(/-/g, '/') : endDT;
  if (startDT) {
    startDT = startDT.indexOf('-') > 0 ? startDT.replace(/-/g, '/') : startDT;
  }

  var date1 = new Date(endDT)
  var date2 = startDT ? new Date(startDT) : new Date();

  var s1 = date1.getTime(), s2 = date2.getTime();
  var total = Math.abs((s2 - s1) / 1000);


  var day = parseInt(total / (24 * 60 * 60));//计算整数天数
  var afterDay = total - day * 24 * 60 * 60;//取得算出天数后剩余的秒数
  var hour = parseInt(afterDay / (60 * 60));//计算整数小时数
  var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60;//取得算出小时数后剩余的秒数
  var min = parseInt(afterHour / 60);//计算整数分
  var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;//取得算出分后剩余的秒数
  var sec = parseInt(afterMin);//计算整数秒
  var strTime = day + "天" + hour + "时" + min + "分" + sec + "秒";
  //console.log('相距时间为：',strTime);
  return {
    day, hour, min, sec
  };
}

const fixZero = n => {
  n = n.toString()
  return ('0' + n).slice(-2);
}


/**
 * [getAddDTOnBasedtime 为指定时间日期增加 diff的 年|月|日|时|分|秒]
 * @param  {[datetimeString]} basedtime [基础时间]
 * @param  {[string]} type      [指定增加类型 year|month|day|hour|minute|second]
 * @param  {[int]} diff      [增量]
 * @return {[datetimeString]}           [newdt 新日期时间]
 */
const getAddDTOnBasedtime = (type, diff, basedtime = '') => {
  // basedtime = basedtime.indexOf('-') > 0 ? basedtime.replace(/-/g, '/') : basedtime; //因为Safari不支持YY-MM-DD的格式，只支持YY/MM/DD,故要转换
  var dt = basedtime ? new Date(basedtime.replace(/-/g, '/')) : new Date();
  switch (type) {
    case 'year':
      dt.setFullYear(dt.getFullYear() + diff);
      break;
    case 'month':
      dt.setMonth(dt.getMonth() + diff);
      break;
    case 'day':
      dt.setDate(dt.getDate() + diff);
      break;
    case 'hour':
      dt.setHours(dt.getHours() + diff);
      break;
    case 'minute':
      dt.setMinutes(dt.getMinutes() + diff);
      break;
    case 'second':
      dt.setSeconds(dt.getSeconds() + diff);
      break;
  }
  var newdtime = dateFormat('yyyy-MM-dd', dt);
  console.log('原时间:', dateFormat(basedtime, 'yyyy-MM-dd hh:mm:ss'), '的', type, '加上', diff, '后的新时间:', newdtime);
  return newdtime;
}

/**
 * 当前月 第一天，星期几
 */
const getFirstDay = (year, month) => {
  let date = new Date(year, month - 1, 1);
  var firstDay = {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    week: date.getDay()
  }
  return firstDay;
}

/**
 * 当前月 最后一天，星期几
 */
const getLastDay = (year, month) => {
  let date = new Date(year, month, 0);
  var lastDay = {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    week: date.getDay()
  }
  return lastDay;
}


/**
 * 当前月 
 * 第一天，星期几
 * 最后一天，星期几
 * 共几天
 */
const getDayInMonth = (year, month) => {
  //第一天
  let date1 = new Date(year, month - 1, 1);
  let firstDate = {
    year: date1.getFullYear(),
    month: date1.getMonth() + 1,
    day: date1.getDate(),
    weekday: date1.getDay()
  }


  //最后一天
  let date2 = new Date(year, month, 0);
  let lastDay = {
    year: date2.getFullYear(),
    month: date2.getMonth() + 1,
    day: date2.getDate(),
    weekday: date2.getDay()
  }

  //共几天
  let days = date2.getDate()

  return {
    from: firstDate,
    to: lastDay,
    days: days
  };
}


const weeks = ['一', '二', '三', '四', '五', '六', '日'];

/**
 * 渲染日历
 */
const render = (year, month, prepareDaysObj = null) => {
  let calendarStr = '';
  let monthArr = []; //二维
  let weekArr = [];
  let fullMonthArr = []; //一维(通用)
  let mObj = getDayInMonth(year, month);

  // 每个月的第一天
  let firstDay = mObj.from.day;
  // 第一天星期几(0-6)
  let weekday = mObj.from.weekday;

  // 每个月的最后一天
  let lastDay = mObj.to.day;
  // 最后一天星期几(0-6)
  let lastDayWeekDay = mObj.to.weekday;

  // 每个月的天数
  let days = mObj.days;

  calendarStr += `👈${year}年${month}月👉\n`;
  calendarStr += weeks.join(' ') + '\n';

  // 补齐前面的空格
  let startLimit = weekday > 0 ? weekday - 1 : 6;
  for (let i = 0; i < startLimit; i++) {
    calendarStr += ' ';
    if (weekArr.length < 7) {
      weekArr.push(' ')
    }

    fullMonthArr.push({
      day: ' ',
      dayDes: ' ',
      weekday: '/',
      weekdayZh: '/',
      days: lastDay,
      date: "",
      ondate: "",
      dateZh: `${year}年${month}月/日`,
      flag: 'PREV',
      holiday: '',
      relax: '',
      isSpecialDay: false,
      status: 0, //预留字段-某日的状态
      style: '', //每日格子自定义样式
    })
  }

  // 正常天显示 
  for (let day = 1; day <= days; day++) {
    console.log('weekday:', weekday)
    calendarStr += day + ' ';
    let ymd = `${year}-${fixZero(month)}-${fixZero(day)}`;
    let ymdZh = `${year}年${fixZero(month)}月${fixZero(day)}日`;
    let holiday = Holiday.getHoliday(ymd);
    let hd = holiday[0];
    let rx = holiday[3];
    let dayObj = {
      day: day,
      dayDes: hd ? hd : day,
      weekday,
      weekdayZh: weeks[weekday],
      days: lastDay,
      date: ymd,
      ondate: ymd,
      dateZh: ymdZh,
      flag: 'CURRENT',
      holiday: hd,
      relax: rx,
      isSpecialDay: hd || weekday === 5 || weekday === 6, //特殊节日+周末
      status: 0, //预留字段-某日的状态
      style: '', //每日格子自定义样式
    };

    // console.log('prepareDaysObj:', prepareDaysObj)

    // 如果客户端传入一(若干)个月的天数组对象
    if (prepareDaysObj && Object.keys(prepareDaysObj).length > 0) {
      let prepareDay = prepareDaysObj[ymd] || {};

      dayObj = Object.assign({}, dayObj, prepareDay);
      // console.log("after assign prepareDaysObj,prepareDay:", dayObj, prepareDay)
    }

    fullMonthArr.push(dayObj);

    // 格式化周显示（换行）
    weekday++
    if (weekday % 7 == 0) {
      weekday = 0;
      calendarStr += '\n';
    }
    if (weekArr.length < 7) {
      weekArr.push(day)
    } else {
      monthArr.push(weekArr)
      weekArr = [day];
    }
    if (day == days) {
      monthArr.push(weekArr)
    }
  }

  // 补齐后面的空格
  let endLimit = lastDayWeekDay > 0 ? 7 - lastDayWeekDay : lastDayWeekDay;
  for (let j = 0; j < 6 - endLimit; j++) {
    calendarStr += ' ';
    if (weekArr.length < 7) {
      weekArr.push(' ')
    }
    fullMonthArr.push({
      day: ' ',
      dayDes: ' ',
      weekday: '/',
      weekdayZh: '/',
      days: lastDay,
      date: "",
      ondate: "",
      dateZh: `${year}年${month}月/日`,
      flag: 'NEXT',
      holiday: '',
      relax: '',
      isSpecialDay: false,
      status: 0, //预留字段-某日的状态
      style: '', //每日格子自定义样式
    })
  }

  calendarStr += '\n\n';

  // console.log(calendarStr)
  // console.log(monthArr)
  // console.log(fullMonthArr)
  // return monthArr;
  return fullMonthArr;
}

export default {
  getDT: getDT,
  getAddDTOnBasedtime: getAddDTOnBasedtime,
  dateFormat: dateFormat,
  diffDate: diffDate,
  getDayInMonth: getDayInMonth,
  weeks: weeks,
  holiday: Holiday.getHoliday.bind(Holiday),
  render: render,
}